const Users = require("../models/Users")

const getUser = async (req, res) => {
    try {
        const userExist = await Users.findOne({ openid: req.user.openid }).select('-_id -openid -session_key -password -id_user').populate({path:"reserves_played",populate:{path:"id_play",populate:"id_drama id_store"}});
        if (userExist) {
            return res.status(200).json({ success: userExist });
        } else {
            return res.status(400).json({ error_msg: "用户不存在" });
        }
    }
    catch (err) {
        return res.status(400).json({ error_msg: err.message });
    }
}

const updateUser = async (req, res) => {
    try {
        const userExist = await Users.findOne({ openid: req.user.openid });
        if (userExist) {
            const savequery = req.body
            for (item in savequery) {
                if (typeof (savequery[item]) == "object") {
                    userExist[item] = { ...userExist[item], ...savequery[item] }
                } else {
                    userExist[item] = savequery[item]
                }
            }
            const userupdated = await userExist.save()
            userupdated._doc._id = undefined
            userupdated.openid = undefined
            userupdated.session_key = undefined
            userupdated.password = undefined

            console.log(userupdated)
            return res.status(200).json({ success: userupdated });
        }
        else {
            return res.status(400).json({ error_msg: "未找到用户" });
        }
    } catch (err) {
        return res.status(400).json({ error_msg: err.message });
    }
}

module.exports = { getUser, updateUser }